const app = getApp()
const get_user_data = require('../../utils/get_user_data.js')

Page({

  /**
   * 页面的初始数据
   */
  data: {
    title: null,
    score_model: [],
    count_idx: 0,
    first_bit_idx: 0,
    second_bit_idx: 0,
    model_idx: 3,
    score_number: null,
    score_time: null,
    average_time: null,
    average_score: null,
    score: null,
    is_new_score: false,
    level: 0,
    is_level_up: false,
    is_max_exp: false,
    exp: 0,
    exp_to_up: 0,
    exp_percent: 0,
    is_exp: false,
    user_data: {},
    user_best_score: 0,
    score_base: 0,
    time_to_score_base: 1,
    is_save: false,
    is_challenge: false,
    test_id: null,
    is_master: false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    let score_model = wx.getStorageSync('score_model')
    let count_idx = score_model[0]
    let first_bit_idx = score_model[1]
    let second_bit_idx = score_model[2]
    let model_idx = score_model[3]
    let test_count = options.test_count
    let title = options.title
    let score_number = +options.score_number
    let test_id = options.test_id
    let is_master = options.is_master
    let score_min = Math.floor(score_number / 60000)
    let score_minsec = score_number % 1000
    let score_sec = (score_number - score_min * 60000 - score_minsec) / 1000
    wx.setNavigationBarTitle({
      title
    })
    if (test_id) {
      this.setData({
        is_master,
        test_id,
        is_challenge: true,
        is_save: true
      })
    }
    this.setData({
      score_model,
      title,
      count_idx,
      first_bit_idx,
      second_bit_idx,
      model_idx,
      is_dark: app.global_data.darkness,
      average_time: '平均' + (score_number / test_count / 1000).toFixed(3) + '秒\/每题',
      score_time: score_min + '分' + score_sec + '秒' + score_minsec,
      score_number,
      average_score: (score_number / test_count / 100000) * 10000000 / 100000
    })
    this.setScoreBase()
  },
  ...get_user_data.methods,
  /* 获取得分基数 */
  setScoreBase() {
    wx.showLoading({
      title: '积分获取中',
    })
    let count_idx = this.data.count_idx
    let first_bit_idx = this.data.first_bit_idx
    let second_bit_idx = this.data.second_bit_idx
    let model_idx = this.data.model_idx
    // count_idx = 0
    // first_bit_idx = 1
    // second_bit_idx = 1
    // model_idx = 4
    let count_base
    let first_base
    let second_base
    let model_base
    let score_base
    let bit_base = (Math.abs(first_bit_idx - second_bit_idx)) + 1
    let time_to_score_base
    if (count_idx < 2) {
      count_base = 10 + count_idx
    } else {
      count_base = 10 + count_idx * count_idx
    }
    if (first_bit_idx < 2) {
      first_base = 1 + first_bit_idx
    } else {
      first_base = first_bit_idx * 2
    }
    if (second_bit_idx < 2) {
      second_base = 1 + second_bit_idx
    } else {
      second_base = second_bit_idx * 2
    }
    if (model_idx < 2) {
      model_base = 1 + model_idx * 0.5
      score_base = (first_base + second_base) * model_base * count_base
      time_to_score_base = (1 + (first_base + second_base + model_base) / 10)
    } else {
      model_base = (first_base + second_base) / bit_base + (model_idx - 2) * (model_idx - 2)
      time_to_score_base = (1 + (first_base + second_base) / 10) + model_base
      score_base = ((Math.abs(first_bit_idx - second_bit_idx)) + 1) * model_base * count_base
    }
    // console.log(score_base)
    // console.log(time_to_score_base)
    this.setData({
      model_idx,
      user_model: [count_idx, first_bit_idx, second_bit_idx],
      score_base: score_base,
      time_to_score_base: time_to_score_base
    })
    this.getUserData(() => {
      this.getUserScore()
    })
  },
  /* 获取用户成绩 */
  getUserScore() {
    let user_best_score
    switch (this.data.model_idx) {
      case 0:
        user_best_score = this.data.user_data.add_best_score
        break
      case 1:
        user_best_score = this.data.user_data.sub_best_score
        break
      case 2:
        user_best_score = this.data.user_data.mul_best_score
        break
      case 3:
        user_best_score = this.data.user_data.div_best_score
        break
      case 4:
        user_best_score = this.data.user_data.mix_best_score
        break
      default:
        break
    }
    this.setData({
      user_best_score: user_best_score
    })
    this.setScore()
  },
  /* 获取得分 */
  setScore() {
    let score = Math.floor(this.data.score_base * this.data.time_to_score_base / this.data.average_score) * 2 + 20
    // console.log(score)
    let score_exp = score / 2
    let exp = score_exp + this.data.user_data.exp
    let level = Math.floor(exp / 100) + this.data.user_data.level
    let exp_to_up = 100 - exp % 100
    let is_level_up = level > this.data.user_data.level
    if (is_level_up) {
      exp = exp % 100
    }
    let is_new_score = score > this.data.user_best_score
    this.setData({
      score,
      is_new_score,
      exp,
      level,
      is_level_up,
      is_exp: !is_level_up,
      exp_to_up
    })
    wx.hideLoading({})
    if (app.global_data.user_data.openid) {
      this.submitScore()
    }
  },
  /* 上传得分 */
  submitScore() {
    let model_label = this.scoreModelLabel()
    let data = {}
    if (this.data.is_new_score) {
      data = `{
        ${model_label.score_label}:${this.data.score},
        ${model_label.count_label}:db.command.inc(1),
        compelete:db.command.inc(1),
        level:${this.data.level},
        exp:${this.data.exp}
      }`
    } else {
      data = `{
        ${model_label.count_label}:db.command.inc(1),
        compelete:db.command.inc(1),
        level:${this.data.level},
        exp:${this.data.exp}
      }`
    }
    wx.cloud.callFunction({
      name: "runDb", //云函数名
      data: {
        type: 'update_user', //指定操作类型
        collection: 'user_data', //修改的集合名称
        data //更新的数据
      },
      success: res => {
        console.log('更新数据成功')
        this.insertScoreRank()
      },
      fail: err => {
        console.error('更新数据失败失败', err)
      }
    })
  },
  insertScoreRank() {
    let data = {
      openid: this.data.user_data.openid,
      name: this.data.user_data.user_info.nickName,
      math_model: this.data.user_model,
      math_label: app.util.modelLabel(this.data.model_idx),
      score: this.data.score,
      score_time: this.data.score_time,
      score_number: this.data.score_number,
      update_time: app.dayjs().valueOf(),
    }
    wx.cloud.callFunction({
      name: "runDb", //云函数名
      data: {
        type: 'insert', //指定操作类型
        collection: 'score_rank', //修改的集合名称
        data //更新的数据
      },
      success: res => {
        console.log('上传得分成功')
        if (this.data.is_challenge) {
          this.insertChallenge()
        }
      },
      fail: err => {
        console.error('上传得分失败', err)
      }
    })
  },
  /* 上传挑战成绩 */
  insertChallenge() {
    let that = this
    let data = {
      user_openid: that.data.user_data.openid,
      user_info: that.data.user_data.user_info,
      test_id: that.data.test_id,
      score: that.data.score,
      score_time: that.data.score_time,
      score_number: that.data.score_number,
      update_time: app.dayjs().valueOf(),
    }
    if (this.data.is_master) {
      wx.showActionSheet({
        itemList: ['霸占挑战榜', '更新数据'],
        success(res) {
          if (res.tapIndex === 0) {
            wx.cloud.callFunction({
              name: "runDb", //云函数名
              data: {
                type: 'insert', //指定操作类型
                collection: 'challenge', //修改的集合名称
                data //更新的数据
              },
              success: res => {
                console.log('上传自己挑战成功')
                wx.showToast({
                  title: '上传成功',
                  icon: 'none'
                })
              },
              fail: err => {
                console.error('上传自己挑战失败', err)
              }
            })
          } else if (res.tapIndex === 1) {
            data = {
              score: that.data.score,
              score_time: that.data.score_time,
              score_number: that.data.score_number,
            }
            wx.cloud.callFunction({
              name: "runDb", //云函数名
              data: {
                type: 'update_detail', //指定操作类型
                collection: 'test', //修改的集合名称
                is_where: {
                  '_id': that.data.test_id
                },
                data //更新的数据
              },
              success: res => {
                wx.showToast({
                  title: '更新成功',
                  icon: 'none'
                })
                console.log('更新题库成功')
              },
              fail: err => {
                console.error('更新题库失败', err)
              }
            })
          }
        },
        fail(res) {
          // console.log(res.errMsg)
        }
      })
      return
    }
    wx.cloud.callFunction({
      name: "runDb", //云函数名
      data: {
        type: 'insert', //指定操作类型
        collection: 'challenge', //修改的集合名称
        data //更新的数据
      },
      success: res => {
        console.log('上传挑战成功')
        if (this.data.is_challenge) {}
      },
      fail: err => {
        console.error('上传得分失败', err)
      }
    })
  },
  /* 保存题库 */
  saveTest() {
    if (!this.data.is_save) {
      let data = {
        master_openid: this.data.user_data.openid,
        title: this.data.title,
        score: this.data.score,
        master: this.data.user_data.user_info,
        score_model: this.data.score_model,
        score_time: this.data.score_time,
        math_label: app.util.modelLabel(this.data.model_idx),
        test: wx.getStorageSync('user_test'),
        update_time: app.dayjs().valueOf()
      }
      // console.log(data)
      wx.cloud.callFunction({
        name: "runDb", //云函数名
        data: {
          type: 'insert', //指定操作类型
          collection: 'test', //修改的集合名称
          data //更新的数据
        },
        success: res => {
          this.setData({
            is_save: true
          })
          wx.showToast({
            title: '上传题目成功',
          })
        },
        fail: err => {
          console.error('上传题目失败', err)
        }
      })
    } else {
      wx.showToast({
        title: '已经上传过了!',
      })
    }
  },
  retryGame() {
    if (this.data.is_challenge) {
      wx.redirectTo({
        url: `/pages/challenge/challenge?id=${this.data.test_id}`,
      })
    } else {
      wx.reLaunch({
        url: `/pages/game/game?title=${this.data.title}`,
      })
    }
  },
  changeModel() {
    wx.switchTab({
      url: '/pages/home/home',
    })
  },
  showExp() {
    this.setData({
      is_exp: true
    })
  },
  scoreModelLabel() {
    let count_label
    let score_label
    switch (this.data.model_idx) {
      case 0:
        score_label = `add_best_score`
        count_label = `add_count`
        break
      case 1:
        score_label = `'sub_best_score'`
        count_label = `'sub_count'`
        break
      case 2:
        score_label = `'mul_best_score'`
        count_label = `'mul_count'`
        break
      case 3:
        score_label = `'div_best_score'`
        count_label = `'div_count'`
        break
      case 4:
        score_label = `mix_best_score`
        count_label = `mix_count`
        break
      default:
        break
    }
    return {
      count_label: count_label,
      score_label: score_label
    }
  },
})